<template>
  <div>
    <el-select v-model="value" :style="`width:${width};`" filterable placeholder="请选择" @change="onValueChange">
      <el-option v-for="(item,i) in options" :key="item.id" :label="item.name" :value="i"></el-option>
    </el-select>
    <el-button type="text" size="small" @click.stop="onRefresh">
      <i class="el-icon-refresh"></i>
    </el-button>
  </div>
</template>

<script>
import { findIndexByKeyValue } from "@/api/common"; //按指定关键字找元素，返回第一个匹配成功的下标
import {
  getMerchantSelectList //url: '/Merchant/GetMerchantSelectList'
} from "@/api/merchant";
export default {
  model: {
    // 使用model， 这儿2个属性:
    prop: "id", //prop属性说，我要将id作为该组件被使用时（此处为aa组件被父组件调用）v-model能取到的值
    event: "to-v-model" //event说，我emit ‘cc’ 的时候，参数的值就是父组件v-model收到的值。
  },
  props: {
    id: { type: Number, default: 0 },
    width:{type:String,default:'93%'}
  },
  data() {
    return {
      options: [],
      value: ""
    };
  },
  created() {
    this.GetList();
  },
  watch: {
    id: function() {
      this.SetInit();
    }
  },
  methods: {
    onRefresh() {
      this.GetList();
    },
    GetList() {
      getMerchantSelectList().then(r => {
        if (r.code == 0) {
          this.options = r.data;
          this.SetInit();
        }
      });
    },
    SetInit() {
      let id = this.$props.id;
      // console.log('子取到的值：',id);
      if (id == 0) {
        this.value = "";
      } else {
        let i = findIndexByKeyValue(this.options, "id", id);
        if (i >= 0) {
          this.value = this.options[i].name;
        }
      }
    },
    onValueChange(index) {
      this.$emit("to-v-model", this.options[index].id); //返回给v-model绑定的变量
      this.$emit("change", this.options[index]);
    }
  }
};
</script>